package org.apimgr.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.UUID;

/**
 * Created by yangjie on 2017/8/2.
 */
public class CommonsUtil {

    private static final Logger logger = LoggerFactory.getLogger(CommonsUtil.class);

    /**
     * 判断字符串是否为空
     * @param strValue
     * @return
     */
    public static boolean isStringEmpty(String strValue) {
        if(strValue == null || "".equals(strValue)) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否不为空
     * @param strValue
     * @return
     */
    public static boolean isStringNotEmpty(String strValue) {
        if(strValue != null && !"".equals(strValue)) {
            return true;
        }
        return false;
    }

    /**
     * 判断集合是否为空
     * @param colValue
     * @return
     */
    public static boolean isCollectionEmpty(Collection colValue) {
        if(colValue == null || colValue.size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断集合是否不为空
     * @param colValue
     * @return
     */
    public static boolean isCollectionNotEmpty(Collection colValue) {
        if(colValue != null && colValue.size() > 0) {
            return true;
        }
        return false;
    }


    /**
     * @return
     * @description 创建UUID唯一键
     */
    public static String createUUID() {
        UUID uuid = UUID.randomUUID();
        String uu = uuid.toString().replaceAll("-", "");
        return uu;
    }

    /**
     * 获取客户端ip
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    logger.error(StringUtils.getErrorInfoFromException(e));
                }
                ip = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
}
